var superagent = require('superagent');

var showRes = true;
var apiHost = 'http://127.0.0.1:3000';
var resProp = ['type', 'charset', 'status', 'body'];

function showTestResponse(res){
  resProp.forEach(function(rp) {
    console.log(rp, res[rp]);
  });
}
function isStatusOk(res){
  return res['status'] == 200;  
}
module.exports.config = function (cfg) {
  if(cfg.apiHost) apiHost = cfg.apiHost;
  if(cfg.hasOwnProperty('showRes')) showRes = cfg.showRes;
  //console.log(apiHost);
};

module.exports.doGetTest = function (testConfig) {
  var url = `${apiHost}${testConfig.url}`;
  superagent.get(url)
    .query(testConfig.reqData).end(function(err, res) {
      if(err) {
        console.error(err);
        return;
      }
      if(showRes){
        console.log(`==doGetTest ${url} over==`);
        showTestResponse(res);
      }
      if(!isStatusOk(res)){
        console.log(url,'test failed','status:',res['status']);
      }      
      if(testConfig.cb) testConfig.cb(res,testConfig);
    });
}

module.exports.doPostTest = function(testConfig) {
  var url = `${apiHost}${testConfig.url}`;
  superagent.post(url).set('Content-Type', 'application/json')
    .send(testConfig.reqData).end(function(err, res) {
      if(err) {
        console.error(err);
        return;
      }
      if(showRes){
        console.log(`==doPostTest ${url} over==`);
        showTestResponse(res); 
      }
      if(!isStatusOk(res)){
        console.log(url,'test failed','status:',res['status']);
      } 
      if(testConfig.cb) testConfig.cb(res,testConfig);
    });
}

module.exports.doPutTest = function(testConfig) {
  var url = `${apiHost}${testConfig.url}`;
  superagent.put(url).set('Content-Type', 'application/json')
    .send(testConfig.reqData).end(function(err, res) {
      if(err) {
        console.error(err);
        return;
      }
      if(showRes){
        console.log(`==doPutTest ${url} over==`);
        showTestResponse(res); 
      }
      if(!isStatusOk(res)){
        console.log(url,'test failed','status:',res['status']);
      } 
      if(testConfig.cb) testConfig.cb(res,testConfig);
    });
}

module.exports.doDeleteTest = function(testConfig) {
  //console.log(`==doDeteteTest, call ${testConfig.url}...`);
  var url = `${apiHost}${testConfig.url}`;
  superagent.delete(url).set('Content-Type', 'application/json')
    .send(testConfig.reqData).end(function(err, res) {
      if(err) {
        console.error(err);
        return;
      }
      if(showRes){
        console.log(`==doDeteteTest ${url} over==`);
        showTestResponse(res);
      }
      if(!isStatusOk(res)){
        console.log(url,'test failed','status:',res['status']);
      } 
      if(testConfig.cb) testConfig.cb(res,testConfig);
    });
}

